<template>
  <div class="box">
    <div class="department-role-manage">
      <el-radio-group
        v-model="active"
        @change="changeTabs"
        size="small"
        class="margin-bottom20"
      >
        <el-radio-button label="department">部门管理</el-radio-button>
        <el-radio-button label="role">角色管理</el-radio-button>
      </el-radio-group>
      <!--部门管理-->
      <el-tree
        v-if="active == 'department'"
        :data="data"
        node-key="id"
        ref="treeBox"
        default-expand-all
        :highlight-current="true"
        @node-click="handleNodeClick"
        :expand-on-click-node="false"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span>{{ data.label }}</span>
          <span>
            <i
              class="el-icon-edit margin-right20"
              @click.stop="() => edit(node, data)"
              v-if="data.parent"
            ></i>
            <!-- <i class="el-icon-delete" @click.stop="() => remove(node, data)" v-if="data.parent"></i> -->
          </span>
        </span>
      </el-tree>
      <!--角色管理-->
      <div class="role-manage" v-else>
        <el-table
          :data="roleList"
          :show-header="false"
          ref="multipleTable"
          @row-click="selectRole"
          border
          id="sort"
          highlight-current-row
        >
          <el-table-column label="名称">
            <template slot-scope="scope">
              <div class="role">
                <div class="role-name">
                  <span>{{ scope.row.label }}</span>
                </div>
                <div>
                  <i
                    class="el-icon-edit"
                    @click.stop="editHandle(scope.row)"
                  ></i>
                  <i
                    class="el-icon-delete  margin-right20 margin-left20"
                    @click.stop="deleteHandle(scope.row)"
                  ></i>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-button
        type="primary"
        @click="appendSubordinate()"
        size="small"
        class="add-subordinate-btn"
        v-if="active == 'department'"
        >新增下级</el-button
      >
      <el-button
        size="small"
        type="primary"
        @click="addRole()"
        class="margin-top20 add-role-btn"
        v-else
        >新增角色</el-button
      >
    </div>
    <div class="department-role-table">
      <el-form label-width="40px" :inline="true">
        <el-form-item label="账号">
          <el-input
            v-model="search.account"
            placeholder="请输入账号"
            clearable
            size="small"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <div class="u-btn-box">
            <el-form-item label="姓名">
              <el-input
                v-model="search.name"
                placeholder="请输入姓名"
                clearable
                size="small"
              ></el-input>
            </el-form-item>
            <el-button type="primary" @click="onSubmit" size="small"
              >搜索</el-button
            >
            <!-- <el-button type="primary" @click="downHandle" size="small">下载模板</el-button>
                <div class="margin-left10 margin-right10">
                <el-upload
                  ref="uploadExl"
                  action
                  multiple
                  :limit="1"
                  :http-request="importObj"
                  :before-upload="beforeUpload"
                  :show-file-list="false"
                >
                  <el-button type="primary" class="u-btn" size="small">批量新增</el-button>
                </el-upload>
              </div> -->
            <el-button type="primary" @click="addHandle" size="small"
              >新增账号</el-button
            >
          </div>
        </el-form-item>
      </el-form>
      <nice-table :data="list" :columns="columns" :pagination="pagination">
        <el-table-column
          label="操作"
          align="center"
          width="200"
          slot="opreation"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button size="small" type="text" @click="editAccount(scope.row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="text"
              @click="closeOrReset(scope.row, 'close')"
              :disabled="!scope.row.open_status"
              >关闭账号</el-button
            >
            <el-button
              size="small"
              type="text"
              @click="closeOrReset(scope.row, 'reset')"
              >重置密码</el-button
            >
          </template>
        </el-table-column>
      </nice-table>
      <add-update-account
        v-if="addAccountDialog"
        ref="addAccount"
        @refreshDataList="getOrganizationalStructureQry"
        :mode="mode"
        :roleList="roleList"
        :departmentList="data"
        :positionList="positionList"
      ></add-update-account>
    </div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      :visible.sync="visible"
      width="500px"
    >
      <el-form :model="form" :rules="formRules" ref="form" label-width="50px">
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入名称"
            clearable
            maxlength="16"
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false" size="small">取消</el-button>
        <el-button type="primary" @click="dataFormSubmit" size="small"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import base from '@/views/base.vue'
import AddUpdateAccount from './add-update-account'
import {
  manageTree,
  tableUpdate,
  downloadTemplateFile,
  importData
} from '@/api/api'
import {
  addSubordinate,
  addRole,
  findEnumTreeByTableNameAndFieldName,
  getOrganizationalStructureQry,
  getNoOrganizationalList
} from '@/api/user'
export default {
  name: 'organize-structure',
  components: {
    AddUpdateAccount
  },
  extends: base,
  data () {
    return {
      data: [],
      departmentId: '',
      department_id: '',
      visible: false,
      positionList: [],
      active: '',
      title: '',
      form: {
        name: ''
      },
      formRules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }]
      },
      roleList: [],
      roles: [],
      row_id: '',
      search: {
        name: '',
        account: ''
      },
      roleId: '',
      addAccountDialog: false,
      mode: '',
      pagination: {
        total: 0,
        pageNum: 1,
        pageSize: 10,
        handleCurrentChange: this.handleCurrentChange,
        handleSizeChange: this.handleSizeChange
      },
      list: [],
      disabed: true,
      columns: [
        {
          label: '账号',
          prop: 'account'
        },
        {
          label: '姓名',
          prop: 'name'
        },
        {
          label: '部门',
          prop: 'department_name'
        },
        // {
        //   label: '岗位',
        //   prop: 'position_name'
        // },
        {
          label: '角色',
          prop: 'role_name'
        },
        {
          label: '状态',
          prop: 'open'
        }
      ]
    }
  },
  activated () {
    this.active = 'department'
    this.getPositionList()
  },
  directives: {
    focus: {
      inserted: function (el) {
        el.querySelector('input').focus()
      }
    }
  },
  methods: {
    async getDepartmentList (departmentId) {
      let res = await manageTree({
        tableName: 'nice_organization'
      })
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        let array = [data.data]
        let response = []
        this.queryList(array, response)
        this.data = this.$deepcopy(response)
        this.$nextTick(() => {
          this.$refs.treeBox.setCurrentKey(this.data[0].id)
          this.departmentId = departmentId || this.data[0].id
          this.pagination.pageNum = 1
          this.pagination.pageSize = 10
          this.getRoleList()
        })
      }
    },
    queryList (tdata, list) {
      if (tdata.length) {
        tdata.forEach((ele, index) => {
          list[index] = {
            label: ele.Name,
            id: ele.id,
            value: ele.id,
            isEdit: false,
            parent: ele.Parent
          }
          let arr = []
          this.queryList(ele.child, arr)
          if (arr.length) {
            list[index].children = arr
          }
        })
      }
    },
    selectRole (row) {
      this.roleId = row.value
      this.pagination.pageNum = 1
      this.pagination.pageSize = 10
      this.getOrganizationalStructureQry()
    },
    deleteHandle (row) {
      this.$confirm('确定删除操作', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.removeRole(row)
        })
        .catch(() => {})
    },
    async removeRole (row) {
      let res = await tableUpdate([
        {
          table_name: 'nice_role',
          update: [{ enable: '1' }],
          where: [{ id: row.value }]
        },
        {
          table_name: 'nice_role',
          update: [{ enable: '1' }],
          where: [{ parent: row.value }]
        }
      ])
      if (res[0]) {
        return
      }
      if (res[1] && res[1].code === 0) {
        this.$message.success('删除角色成功！')
        this.getRoleList()
      } else {
        this.$message.error(res[1].msg)
      }
    },
    // 批量新增
    async importObj (e) {
      let formData = new FormData()
      formData.append('file', e.file)
      let res = await importData(formData)
      if (res[0]) {
        return
      }
      this.getOrganizationalStructureQry()
      this.$ref.uploadExl.clearFiles()
    },
    // 上传验证
    beforeUpload (file) {
      const isExcel =
        file.type === 'application/vnd.ms-excel' ||
        file.type ===
          'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      const isLt100M = file.size / 1024 / 1024 < 200

      if (!isExcel) {
        this.$message.error('上传的文件只能是 xls 或 xlsx 格式!')
      }
      if (!isLt100M) {
        this.$message.error('上传的文件大小不能超过 200MB!')
      }
      return isExcel && isLt100M
    },
    async getPositionList () {
      let res = await findEnumTreeByTableNameAndFieldName({
        tableName: 'nice_inner_user',
        fieldName: 'position_id'
      })
      if (res[0]) {
      }
      let data = res[1]
      if (data && data.code === 0) {
        let array = [data.data]
        let response = []
        this.positionsQueryList(array, response)
        this.positionList = this.$deepcopy(response)
        this.getDepartmentList()
      } else {
        this.$message.error(data.msg)
      }
    },
    positionsQueryList (tdata, list) {
      if (tdata.length) {
        tdata.forEach((ele, index) => {
          list[index] = {
            label: ele.display_value,
            value: ele.t_id,
            parent: ele.parent
          }
          let arr = []
          this.positionsQueryList(ele.child, arr)
          if (arr.length) {
            list[index].children = arr
          }
        })
      }
    },
    async getRoleList () {
      let res = await manageTree({
        tableName: 'nice_role'
      })
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        if (data.data.hasOwnProperty('child')) {
          this.roleList = data.data.child.map(ele => {
            return {
              label: ele.role_name,
              value: String(ele.id)
            }
          })
          this.roleId = this.roleId || this.roleList[0].value
          if (this.active === 'role') {
            this.$nextTick(() => {
              this.$refs.multipleTable.setCurrentRow(
                this.$refs.multipleTable.data[0]
              )
            })
          }
          this.pagination.pageNum = 1
          this.pagination.pageSize = 10
          this.getOrganizationalStructureQry()
        }
      } else {
        this.$message.error(res[1].msg)
      }
    },
    async getOrganizationalStructureQry () {
      let res = []
      if (this.active === 'department' && this.departmentId === -1) {
        res = await getNoOrganizationalList({
          table_name: 'nice_inner_user',
          condition: [
            {
              'nice_inner_user_nice_user_base.real_name': [
                {
                  like: this.search.name
                }
              ]
            },
            {
              'nice_inner_user_sys_user.username': [
                {
                  like: this.search.account
                }
              ]
            }
          ],
          by_order: 'create_time desc',
          member: 'user_type,name,role,job,department_name,account,open_status',
          by_page: {
            currPage: this.pagination.pageNum,
            pageSize: this.pagination.pageSize
          }
        })
      } else {
        res = await getOrganizationalStructureQry({
          real_name: this.search.name,
          nice_role_id: this.active === 'department' ? '' : this.roleId,
          department_id: this.active === 'department' ? this.departmentId : '',
          username: this.search.account,
          currPage: this.pagination.pageNum,
          pageSize: this.pagination.pageSize
        })
      }
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        this.pagination.total = data.data.totalCount
        if (data.data.list && data.data.list.length) {
          data.data.list.forEach(ele => {
            ele.position_name = this.$filterTree(
              ele.position_id,
              this.positionList
            )
            ele.department_name = this.$filterTree(ele.department_id, this.data)
            ele.open = ele.open_status === 1 ? '已开通' : '已关闭'
            this.roles = []
            if (ele.role) {
              ele.role.split(',').forEach(role => {
                this.roleList.forEach(item => {
                  if (+role == item.value) {
                    this.roles.push(item.label)
                  }
                })
              })
              ele.role_name = this.roles.join(',')
            }
          })
        }
        this.list = data.data.list
      } else {
        this.$message.success(data.msg)
      }
    },
    changeTabs () {
      if (this.active === 'department') {
        this.getDepartmentList()
      } else {
        this.getRoleList()
      }
    },
    dataFormSubmit () {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.submit()
        }
      })
    },
    async submit () {
      let res =
        this.title === '新增下级'
          ? await addSubordinate({
            'nice_organization.Name': this.form.name,
            'nice_organization.Parent': this.departmentId
          })
          : this.title === '新增角色'
          ? await addRole({
            'nice_role.role_name': this.form.name,
            'nice_role.parent': '1'
          })
          : this.title === '编辑部门'
          ? await tableUpdate([
            {
              table_name: 'nice_organization',
              update: [
                {
                  Name: this.form.name
                }
              ],
              where: [
                {
                  id: this.department_id
                }
              ]
            }
          ])
          : await tableUpdate([
            {
              table_name: 'nice_role',
              update: [
                {
                  role_name: this.form.name
                }
              ],
              where: [
                {
                  id: this.row_id
                }
              ]
            }
          ])
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        this.$message({
          message:
            this.title === '新增下级' || this.title === '新增角色'
              ? '新增成功'
              : '编辑成功',
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.title === '新增下级' || this.title === '编辑部门'
              ? this.getDepartmentList()
              : this.getRoleList()
            this.visible = false
          }
        })
      } else {
        this.$message.error(data.msg)
      }
    },
    editHandle (item) {
      this.title = '编辑角色'
      this.form.name = item.label
      this.row_id = item.value
      this.init()
    },
    // 点击每个节点
    handleNodeClick (data) {
      this.departmentId = data.id
      this.pagination.pageNum = 1
      this.pagination.pageSize = 10
      this.getOrganizationalStructureQry()
    },
    // 增加下级
    async appendSubordinate () {
      this.title = '新增下级'
      this.form.name = ''
      this.init()
    },
    async addRole () {
      this.title = '新增角色'
      this.form.name = ''
      this.init()
    },
    init () {
      this.visible = true
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    },
    // 删除
    remove (node, data) {
      this.$confirm('确定删除操作', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.removeOrganize(data)
        })
        .catch(() => {})
    },
    async removeOrganize (data) {
      let res = await tableUpdate([
        {
          table_name: 'nice_organization',
          update: [
            {
              enable: '1'
            }
          ],
          where: [
            {
              id: data.id
            }
          ]
        },
        {
          table_name: 'nice_organization',
          update: [
            {
              enable: '1'
            }
          ],
          where: [
            {
              parent: data.id
            }
          ]
        }
      ])
      if (res[0]) {
        return
      }
      if (res[1] && res[1].code === 0) {
        this.getDepartmentList()
      } else {
        this.$message.error(res[1].msg)
      }
    },
    editAccount (row) {
      if (this.roleList.length === 0) {
        this.getRoleList()
      }
      this.addAccountDialog = true
      this.mode = 'edit'
      this.$nextTick(() => {
        this.$refs.addAccount.init(row)
      })
    },
    // 编辑
    edit (node, data) {
      this.title = '编辑部门'
      this.form.name = data.label
      this.department_id = data.id
      this.init()
    },
    closeOrReset (row, label) {
      this.$confirm(
        `确定进行${label === 'close' ? '关闭账号' : '重置密码'}操作？`,
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          this.close(row.user_id, label)
        })
        .catch(() => {})
    },
    async close (id, label) {
      let res = await tableUpdate([
        {
          table_name: 'sys_user',
          update: [
            label === 'close'
              ? { status: '0' }
              : {
                password:
                    '24dd82970a462b7da6a55dea5022d1312205f561076e2553e48923ba3b1a8d31',
                salt: 'wFwbvuBIHPY7T5qGQytf'
              }
          ],
          where: [
            {
              user_id: id
            }
          ]
        }
      ])
      if (res[0]) {
        return
      }
      let data = res[1]
      if (data && data.code === 0) {
        this.$message({
          message: `${label === 'close' ? '关闭账号' : '重置密码'}成功`,
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.getOrganizationalStructureQry()
          }
        })
      } else {
        this.$message.error(data.msg)
      }
    },
    onSubmit () {
      this.pagination.pageNum = 1
      this.getOrganizationalStructureQry()
    },
    handleCurrentChange (val) {
      this.pagination.pageNum = val
      this.getOrganizationalStructureQry()
    },
    handleSizeChange (val) {
      this.pagination.pageSize = val
      this.getOrganizationalStructureQry()
    },
    async downHandle () {
      let res = await downloadTemplateFile({
        data: [
          {
            header: '姓名(必填)',
            tableandfield: 'sys_user.sys_user_nice_user_base.real_name'
          },
          {
            header: '联系方式(必填)',
            tableandfield:
              'sys_user.username:sys_user.sys_user_nice_user_base.mobile'
          },
          {
            header: '部门(必填)',
            tableandfield: 'sys_user.sys_user_nice_inner_user.department_id'
          },
          {
            header: '岗位(必填)',
            tableandfield: 'sys_user.sys_user_nice_inner_user.position_id'
          },
          {
            header: '角色(必填)',
            tableandfield: 'sys_user.sys_user_nice_user_role.nice_role_id'
          },
          {
            header: '用户类型(必填)',
            tableandfield:
              'sys_user.user_type:sys_user.sys_user_nice_user_base.user_type'
          }
        ]
      })
      if (res.status === 200) {
        let filename = decodeURI('账号模板下载.xls')
        filename = filename.replace(/\"/g, '')
        this.$downloadExcel(res.data, filename)
      }
    },
    addHandle () {
      this.addAccountDialog = true
      this.mode = 'add'
      if (this.roleList.length === 0) {
        this.getRoleList()
      }
      this.$nextTick(() => {
        this.$refs.addAccount.init()
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.box {
  display: flex;
  .u-btn-box {
    display: -webkit-box;
  }
  .u-btn {
    font-size: 12px;
  }
  .department-role-manage {
    width: 300px;
    text-align: center;
    .el-tree {
      height: 500px;
      overflow: auto;
    }
    .add-role-btn {
      width: 100%;
    }
    .add-subordinate-btn {
      width: 100%;
      margin: 20px 0px;
    }
  }
  .department-role-table {
    flex: 1;
    margin-left: 30px;
    overflow: auto;
  }
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  .role-manage {
    height: 560px;
    overflow: auto;
    .role {
      display: flex;
      justify-content: space-between;
      .role-name {
        width: 60%;
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
      }
    }
  }
}
</style>
